package com.itheima.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

@Component
public class FeignInterceptor implements RequestInterceptor {


    @Override
    public void apply(RequestTemplate requestTemplate) {
        //获取到请求信息
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        //获取到所有请求头的key
        Enumeration<String> headerNames = request.getHeaderNames();

        //判空
        if (headerNames!=null){
            //遍历 并将对应的header的值取出来 通过requestTemplate的方法传入到下一个调用的服务中
            while (headerNames.hasMoreElements()){
                String headerName=headerNames.nextElement();
                String headerValue=request.getHeader(headerName);
                requestTemplate.header(headerName,headerValue);
            }
        }


    }
}
